﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Commons.ViewModels.PriceStep;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Result;
using Atmk.WaterMeter.MIS.TestForm.Common;
using Atmk.WaterMeter.MIS.TestForm.Dialogs;
using Common.Logging;
using Newtonsoft.Json;
using NKnife.IoC;
using RestSharp;
using WeifenLuo.WinFormsUI.Docking;

namespace Atmk.WaterMeter.MIS.TestForm.Views.XiangZhanAo
{
    public partial class PriceStepView : DockContent
    {
        private readonly Kernel _kernel;
        private static readonly ILog _Logger = LogManager.GetLogger<PriceStepView>();
        private string _projectId;
        private PriceStepAndMeterTypeData _priceStepAndMeterTypeResult;

        public PriceStepView()
        {
            _kernel = DI.Get<Kernel>();
            InitializeComponent();

            BindClick();
        }

        private void BindClick()
        {
            _ProjectIdBtn.Click += (s, e) => { GetProjectId(); };
            _PriceStepListBtn.Click += (s, e) => { GetPriceStepInfo(); };
            _AddPriceBtn.Click += (s, e) => { AddPrice(); };
            _AddFeeBtn.Click += (s, e) => { AddFee(); };
            _MeterTypelistBox.SelectedIndexChanged+=(s, e) => { GetPriceStepInfo(((ListBox)s).SelectedItem.ToString()); };
        }

        private void GetPriceStepInfo(string meterType)
        {
            var kernel = DI.Get<Kernel>();
            var resoure = UrlManager.GetPriceStepByMeterType;
            var request = new RestRequest(resoure, Method.POST);
            request.AddHeader("X-Token", _kernel.Token);
            request.AddJsonBody(new { projectId =_projectId, meterType});
            kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                try
                {
                    _Logger.Debug(data);
                    var result = JsonConvert.DeserializeObject<PrictStepDataResult>(data);
                    _Logger.Trace(result.data);
                    BindData(result.data);
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private void AddFee()
        {
            var request = new RestRequest(UrlManager.AddFee, Method.POST);
            request.AddHeader("X-Token", _kernel.Token);
            string priceId;
            try
            {
                priceId = _DgvPrice.SelectedRows[0].Cells[0].Value.ToString();
            }
            catch (Exception e)
            {
                _Logger.Error(e);
                return;
            }
            var d = new FeePricePost
            {
                index = $"{_DgvFee.RowCount + 1}",
                title = $"{_MeterTypelistBox.SelectedItem.ToString()}费用",
                priceId = priceId,
                price1 = 1,
                price2 = 2,
                price3 = 3,
                remark = ""
            };
            request.AddJsonBody(d);
            _kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                _Logger.Trace(data);
                try
                {
                    var ret = JsonConvert.DeserializeObject<BaseResult>(data);
                    _Logger.Trace(ret.errcode == 0 ? $"{d.ToString()}创建成功" : $"{d.ToString()}创建失败");
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private void AddPrice()
        {
            var request = new RestRequest(UrlManager.AddPriceStep, Method.POST);
            request.AddHeader("X-Token", _kernel.Token);

            var d = new PrictStepPost
            {
                index = $"{_DgvPrice.RowCount + 1}",
                projectId = _projectId,
                title = $"{_MeterTypelistBox.SelectedItem.ToString()}水价",
                meterType = _MeterTypelistBox.SelectedItem.ToString(),
                separation1 = 16,
                separation2 = 26,
                unit = "元/吨",
                remark = ""
            };
            request.AddJsonBody(d);
            _kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                _Logger.Trace(data);
                try
                {
                    var ret = JsonConvert.DeserializeObject<BaseResult>(data);
                    _Logger.Trace(ret.errcode == 0 ? $"{d.ToString()}创建成功" : $"{d.ToString()}创建失败");
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private void GetProjectId()
        {
            var request = new RestRequest(UrlManager.GetUserInfo, Method.GET);
            request.AddHeader("X-Token", _kernel.Token);
            _kernel.Client.ExecuteAsync(request, response =>
            {
                _Logger.Trace(response.ResponseUri.AbsoluteUri);
                _Logger.Debug(response.Content);
                try
                {
                    var result = JsonConvert.DeserializeObject<LoginDialog.UserInfoResult>(response.Content);
                    _projectId = result.data.projectId;
                    _Logger.Trace(_projectId);
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private void GetPriceStepInfo()
        {
            var kernel = DI.Get<Kernel>();
            var resoure = UrlManager.GetPriceStep + (_projectId.Length > 0 ? $"/{_projectId}" : "");
            var request = new RestRequest(resoure, Method.GET);
            request.AddHeader("X-Token", _kernel.Token);
            kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                try
                {
                    _Logger.Debug(data);
                    var result = JsonConvert.DeserializeObject<PrictStepDataMeterTypeResult>(data);

                    _priceStepAndMeterTypeResult = result.data;
                    _Logger.Trace(_priceStepAndMeterTypeResult.meterList);
                    BindData(_priceStepAndMeterTypeResult);
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }


        private void BindData(IData data)
        {
            if (data is PriceStepAndMeterTypeData andMeterTypeData)
            {
                Invoke((EventHandler) delegate
                {
                    BindMeter(andMeterTypeData.meterList);
                    BindPriceStep(andMeterTypeData.priceList);
                    BindFeeStep(andMeterTypeData.feeList);
                });
            }
            if (data is PriceStepData priceStepData)
            {
                Invoke((EventHandler)delegate
                {
                    BindPriceStep(priceStepData.priceList);
                    BindFeeStep(priceStepData.feeList);
                });
            }
        }

        private void BindFeeStep(List<PriceStepFeeItem> dataFeeList)
        {
            var dt = new DataTable();
            var columnNames = new List<string> {"id", "价格Id", "序号", "费用名称", "单价1", "单价2", "单价3", "备注"};
            dt.Columns.AddRange(columnNames.Select(c => new DataColumn(c)).ToArray());
            foreach (var item in dataFeeList)
            {
                var dr = dt.NewRow();
                dr[0] = item.id;
                dr[1] = item.priceId;
                dr[2] = item.index;
                dr[3] = item.title;
                dr[4] = item.price1;
                dr[5] = item.price2;
                dr[6] = item.price3;
                dr[7] = item.remark;
                dt.Rows.Add(dr);
            }
            _DgvFee.DataSource = dt;
            _DgvFee.Columns[0].Visible = false;
            _DgvFee.Columns[1].Visible = false;
        }

        private void BindPriceStep(List<PriceStepItem> dataPriceList)
        {
            var dt = new DataTable();
            var columnNames =
                new List<string> {"id", "序号", "价格名称", "水表类型", "单价1", "单价2", "单价3", "分界点1", "分界点2", "单位", "备注"};
            dt.Columns.AddRange(columnNames.Select(c => new DataColumn(c)).ToArray());
            foreach (var item in dataPriceList)
            {
                var dr = dt.NewRow();
                dr[0] = item.id;
                dr[1] = item.index;
                dr[2] = item.title;
                dr[3] = item.meterType;
                dr[4] = item.price1;
                dr[5] = item.price2;
                dr[6] = item.price3;
                dr[7] = item.separation1;
                dr[8] = item.separation2;
                dr[9] = item.unit;
                dr[10] = item.remark;
                dt.Rows.Add(dr);
            }
            _DgvPrice.DataSource = dt;
            _DgvPrice.Columns[0].Visible = false;
        }

        private void BindMeter(List<string> dataMeterList)
        {
            _MeterTypelistBox.DataSource = dataMeterList;
        }
    }

    public class PrictStepDataMeterTypeResult : BaseResult
    {
        public PriceStepAndMeterTypeData data { get; set; }
    }
    public class PrictStepDataResult : BaseResult
    {
        public PriceStepData data { get; set; }
    }
    public class PrictStepPost
    {
        public string projectId { get; set; } //项目id
        public string index { get; set; } //显示序号
        public string title { get; set; } //价格名称
        public string meterType { get; set; } //显示水表类型
        public double separation1 { get; set; } //分界点1
        public double separation2 { get; set; } //分界点2
        public string unit { get; set; } //单位
        public string remark { get; set; } //备注
    }

    public class FeePricePost
    {
        public string priceId { get; set; } //阶梯价格的id
        public string index { get; set; } //显示序号
        public string title { get; set; } //费用名称
        public double price1 { get; set; } //单价1
        public double price2 { get; set; } //单价2
        public double price3 { get; set; } //单价3
        public string remark { get; set; } //备注
    }
}